const fs = require('fs')
const path = require('path')
const { query, execute } = require('../config/database')

// 解析斗罗大陆文本文件
async function parseAndImportDouluodalu () {
  try {
    console.log('✅ 开始导入斗罗大陆')

    // 读取文本文件
    const filePath = path.join(__dirname, '../../斗罗大陆.txt')
    const content = fs.readFileSync(filePath, 'utf8')
    console.log(
      '✅ 文件读取成功，文件大小：',
      Math.round(content.length / 1024),
      'KB'
    )

    // 首先查找斗罗大陆小说的ID，如果不存在则创建
    const novels = await query('SELECT id FROM novels WHERE title = ?', [
      '斗罗大陆'
    ])

    let novelId
    if (novels.length === 0) {
      // 创建斗罗大陆小说记录
      const [result] = await execute(
        `
        INSERT INTO novels (title, author, description, category, tags, status, word_count, chapter_count, rating, view_count, like_count)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `,
        [
          '斗罗大陆',
          '唐家三少',
          '唐门外门弟子唐三，因偷学内门绝学为唐门所不容，跳崖明志时却来到了另一个世界，一个属于武魂的世界。名叫斗罗大陆。',
          'fantasy',
          JSON.stringify(['玄幻', '武魂', '修炼', '唐家三少']),
          'completed',
          0, // 字数稍后更新
          0, // 章节数稍后更新
          9.2,
          1500000,
          80000
        ]
      )
      novelId = result.insertId
      console.log('✅ 创建斗罗大陆小说记录，ID：', novelId)
    } else {
      novelId = novels[0].id
      console.log('✅ 找到斗罗大陆小说记录，ID：', novelId)
    }

    // 清除已存在的章节
    await execute('DELETE FROM chapters WHERE novel_id = ?', [novelId])
    console.log('✅ 清除旧章节数据')

    // 解析章节
    const chapters = parseChapters(content)
    console.log('✅ 解析完成，共找到', chapters.length, '个章节')

    // 批量插入章节
    let insertedCount = 0
    for (let i = 0; i < chapters.length; i++) {
      const chapter = chapters[i]

      try {
        await execute(
          `
          INSERT INTO chapters (novel_id, title, content, chapter_number, word_count, is_vip, price)
          VALUES (?, ?, ?, ?, ?, ?, ?)
        `,
          [
            novelId,
            chapter.title,
            chapter.content,
            chapter.chapterNumber,
            chapter.wordCount,
            chapter.chapterNumber > 5 ? 1 : 0, // 前5章免费
            chapter.chapterNumber > 5 ? 5 : 0 // VIP章节5书币
          ]
        )

        insertedCount++
        if (insertedCount % 10 === 0) {
          console.log(`📄 已导入 ${insertedCount}/${chapters.length} 章节`)
        }
      } catch (error) {
        console.error(`❌ 导入第${chapter.chapterNumber}章失败:`, error.message)
      }
    }

    // 更新小说统计信息
    const totalWordCount = chapters.reduce((sum, ch) => sum + ch.wordCount, 0)
    await execute(
      `
      UPDATE novels 
      SET word_count = ?, chapter_count = ?
      WHERE id = ?
    `,
      [totalWordCount, chapters.length, novelId]
    )

    console.log('✅ 导入完成！')
    console.log(`📊 统计信息:`)
    console.log(`   - 总章节数: ${chapters.length}`)
    console.log(`   - 总字数: ${totalWordCount.toLocaleString()}`)
    console.log(`   - 成功导入: ${insertedCount}`)
  } catch (error) {
    console.error('❌ 导入失败:', error)
  }
}

// 解析章节内容
function parseChapters (content) {
  const chapters = []

  // 使用正则表达式匹配章节标题
  // 匹配模式：绗.*绔?（繁体中文的"第...章"）
  const chapterRegex = /绗[^绔?]*绔?[^绗]*/g
  const matches = content.match(chapterRegex)

  if (!matches) {
    console.log('⚠️ 未找到章节标题模式，尝试按段落分割')
    return parseByParagraphs(content)
  }

  console.log(
    '📖 找到章节标题:',
    matches.slice(0, 5).map(m => m.substring(0, 30))
  )

  // 找到所有章节开始位置
  const chapterPositions = []
  let lastIndex = 0

  for (let i = 0; i < matches.length; i++) {
    const match = matches[i]
    const index = content.indexOf(match, lastIndex)
    if (index !== -1) {
      chapterPositions.push({
        index,
        title: cleanTitle(match),
        chapterNumber: i + 1
      })
      lastIndex = index + match.length
    }
  }

  // 提取每个章节的内容
  for (let i = 0; i < chapterPositions.length; i++) {
    const currentChapter = chapterPositions[i]
    const nextChapter = chapterPositions[i + 1]

    const startIndex = currentChapter.index
    const endIndex = nextChapter ? nextChapter.index : content.length

    let chapterContent = content.substring(startIndex, endIndex)

    // 清理内容
    chapterContent = cleanContent(chapterContent)

    // 计算字数
    const wordCount = chapterContent.replace(/\s/g, '').length

    if (wordCount > 100) {
      // 只保留有实际内容的章节
      chapters.push({
        title: currentChapter.title,
        content: chapterContent,
        chapterNumber: currentChapter.chapterNumber,
        wordCount: wordCount
      })
    }
  }

  return chapters
}

// 按段落分割（备用方案）
function parseByParagraphs (content) {
  const paragraphs = content.split(/\n\s*\n/).filter(p => p.trim().length > 100)
  const chapters = []

  for (let i = 0; i < Math.min(paragraphs.length, 50); i++) {
    // 最多50章
    const paragraph = paragraphs[i].trim()
    chapters.push({
      title: `第${i + 1}章`,
      content: cleanContent(paragraph),
      chapterNumber: i + 1,
      wordCount: paragraph.replace(/\s/g, '').length
    })
  }

  return chapters
}

// 清理标题
function cleanTitle (title) {
  return title
    .replace(/绗/g, '第')
    .replace(/绔?/g, '章')
    .replace(/\s+/g, ' ')
    .trim()
    .substring(0, 100) // 限制标题长度
}

// 清理内容
function cleanContent (content) {
  return content
    .replace(/澹版槑锛?.*?-------------------------------/gs, '') // 移除声明
    .replace(/\[.*?\]/g, '') // 移除方括号内容
    .replace(/銆€銆€/g, '\n    ') // 替换繁体空格
    .replace(/\s+/g, ' ') // 合并多个空格
    .replace(/\n\s*\n/g, '\n\n') // 规范化段落分隔
    .trim()
}

// 执行导入
if (require.main === module) {
  parseAndImportDouluodalu()
    .then(() => {
      console.log('🎉 斗罗大陆导入完成！')
      process.exit(0)
    })
    .catch(error => {
      console.error('💥 导入失败:', error)
      process.exit(1)
    })
}

module.exports = { parseAndImportDouluodalu }
